<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 数据模型
// +----------------------------------------------------------------------
namespace Inphp\Core\Db\PDO;

use Inphp\Core\Db\Db;

abstract class Model
{
    /**
     * 表名
     * @var string
     */
    protected string $tableName = 'tableName';

    /**
     * 主键字段名称
     * @var string
     */
    protected string $primaryKey = "id";

    /**
     * 表别名
     * @var string
     */
    protected string $as = "";

    /**
     * 获取表名
     * @param bool $fullName
     * @return string
     */
    public function getTableName(bool $fullName = false): string
    {
        return ($fullName ? Db::getTablePrefix() : "").$this->tableName;
    }

    /**
     * 如果当作字符串，直接输出表名即可
     * @return string
     */
    public function __toString(): string
    {
        // TODO: Implement __toString() method.
        return $this->tableName;
    }

    /**
     * 开始一个
     * @param string|bool $as
     * @return Query
     */
    public static function emptyQuery(string|bool $as = false): Query
    {
        $m = new static();
        return Db::from($m->tableName, (is_string($as) ? $as : ($as ? $m->as : "")));
    }

    /**
     * 获取
     * @param bool $fullName
     * @return string
     */
    public static function tableName(bool $fullName = false): string
    {
        return (new static())->getTableName($fullName);
    }

    /**
     * 别名
     * @param string $name
     * @param bool $fullName
     * @return string
     */
    public static function as(string $name, bool $fullName = false): string
    {
        return self::tableName($fullName)." ".$name;
    }

    /**
     * 获取一行数据
     * @param $value
     * @return array|null
     */
    public static function getRowByPrimaryKey($value): array|null
    {
        $m = new static();
        return Db::from($m->tableName)->where($m->primaryKey, $value)->first();
    }
}